package com.zzyl.nursing.service.imp;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;
    @Override
    public String getOpenid(UserLoginRequestDto loginRequestDto) {
        Map<String,Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);
        // wx.login()传过来的code值，有效期为5分钟，且只能使用一次
        params.put("js_code",loginRequestDto.getCode());
        params.put("grant_type","authorization_code");
        HttpResponse res = HttpUtil.createRequest(Method.GET, REQUEST_URL)
                .form(params)
                .execute();

        String openId = JSONUtil.parseObj(res.body()).get("openid", String.class);
        return openId;
    }

    @Override
    public String getPhone(String detailCode) {
        String accessToken = getAccessToken();
        //1、请求路径
        String url = PHONE_REQUEST_URL + accessToken;
        //2、请求参数
        Map<String,Object> params = new HashMap<>();
        params.put("code",detailCode);
        //3、发送请求
        HttpResponse res = HttpUtil.createRequest(Method.POST, url)
                // 请求体 json
                .body(JSONUtil.toJsonStr(params))
                .execute();


        String resultJson = res.body();
        JSONObject json = JSONUtil.parseObj(resultJson);
        Integer errcode = json.get("errcode", Integer.class);
        if(null == errcode || 0==errcode.intValue()){
            return json.getByPath("phone_info.purePhoneNumber", String.class);
        }
        throw new ServiceException("获取手机号出错");
    }

    private String getAccessToken(){
        //存储到redis中，设置过期时间 @Cacheable不能设置所以使用，rediscache  todo
        //2、请求参数
        Map<String,Object> params = new HashMap<>();
        params.put("appid",appid);
        params.put("secret",secret);

        //3、发送请求
        HttpResponse res = HttpUtil.createRequest(Method.GET, TOKEN_URL)
                //?key=value
                .form(params)
                .execute();
        //4、解析结果


        String resultJson = res.body();
        JSONObject json = JSONUtil.parseObj(resultJson);
        Integer errcode = json.get("errcode", Integer.class);
        if(null == errcode || 0== errcode){
            return json.get("access_token", String.class);
        }

        throw new ServiceException("获取access_token出错");
    }
}
